import React, { useState, useEffect, useContext } from 'react';
import { Class } from '../../../shared/models';
import { DataContext } from '../../../shared/DataContext';

interface AddEditClassModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSave: (classData: Class) => void;
  initialData: Class | null;
  isEditing: boolean;
}

const AddEditClassModal: React.FC<AddEditClassModalProps> = ({
  isOpen,
  onClose,
  onSave,
  initialData,
  isEditing
}) => {
  // 从数据上下文获取选项数据
  const { stageOptions, academyOptions } = useContext(DataContext)!;

  const subjectOptions = [
    { value: 'chinese', label: '语文' },
    { value: 'math', label: '数学' },
    { value: 'english', label: '英语' },
    { value: 'physics', label: '物理' },
    { value: 'chemistry', label: '化学' },
    { value: 'biology', label: '生物' },
    { value: 'history', label: '历史' },
    { value: 'geography', label: '地理' },
    { value: 'politics', label: '政治' }
  ];

  const statusOptions = [
    { value: 'active', label: '在读' },
    { value: 'graduated', label: '已毕业' },
    { value: 'disbanded', label: '已解散' },
    { value: 'pending', label: '待审核' }
  ];

  const [classData, setClassData] = useState<Class>({
    id: '',
    name: '',
    stage: '',
    academy: '',
    headTeacherId: '',
    headTeacherName: '',
    subjects: [],
    status: 'active',
    createdAt: '',
    updatedAt: ''
  });

  const [errors, setErrors] = useState<{ [key: string]: string }>({});

  // 初始化表单数据
  useEffect(() => {
    if (isOpen) {
      if (isEditing && initialData) {
        setClassData({ ...initialData });
      } else {
        setClassData({
          id: '',
          name: '',
          stage: '',
          academy: '',
          headTeacherId: '',
          headTeacherName: '',
          subjects: [],
          status: 'active',
          createdAt: new Date().toISOString().split('T')[0],
          updatedAt: new Date().toISOString().split('T')[0]
        });
      }
      setErrors({});
    }
  }, [isOpen, isEditing, initialData]);

  // 处理表单输入变化
  const handleChange = (field: string, value: any) => {
    setClassData(prev => ({
      ...prev,
      [field]: value,
      updatedAt: new Date().toISOString().split('T')[0]
    }));
    // 清除该字段的错误
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: '' }));
    }
  };

  // 处理科目选择变化
  const handleSubjectChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const options = e.target.selectedOptions;
    const values = Array.from(options).map(option => option.value);
    handleChange('subjects', values);
  };

  // 移除已选科目
  const removeSubject = (subject: string) => {
    handleChange('subjects', (classData.subjects || []).filter(s => s !== subject));
  };

  // 验证表单
  const validateForm = (): boolean => {
    const newErrors: { [key: string]: string } = {};

    if (!classData.id.trim()) {
      newErrors.id = '请输入班级编号';
    }

    if (!classData.name.trim()) {
      newErrors.name = '请输入班级名称';
    }

    if (!classData.stage) {
      newErrors.stage = '请选择阶段';
    }

    if (!classData.academy) {
      newErrors.academy = '请选择学院';
    }

    if (!classData.headTeacherName.trim()) {
      newErrors.headTeacherName = '请输入班主任姓名';
    }

    if ((classData.subjects || []).length === 0) {
      newErrors.subjects = '请至少选择一个科目';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 处理保存
  const handleSave = () => {
    if (validateForm()) {
      onSave(classData);
    }
  };

  // 处理模态框点击外部关闭
  const handleOverlayClick = (e: React.MouseEvent) => {
    if (e.target === e.currentTarget) {
      onClose();
    }
  };

  if (!isOpen) return null;

  return (
    <div className="modal-overlay" onClick={handleOverlayClick}>
      <div className="modal">
        <div className="modal-header">
          <h2>{isEditing ? '编辑班级' : '添加班级'}</h2>
          <button className="close-btn" onClick={onClose}>×</button>
        </div>
        <div className="modal-body">
          <div className="form-group">
            <label htmlFor="id">班级编号 *</label>
            <input
              type="text"
              id="id"
              value={classData.id}
              onChange={(e) => handleChange('id', e.target.value)}
              disabled={isEditing}
              placeholder="请输入班级编号"
            />
            {errors.id && <span style={{ color: 'red', fontSize: '12px' }}>{errors.id}</span>}
          </div>

          <div className="form-group">
            <label htmlFor="name">班级名称 *</label>
            <input
              type="text"
              id="name"
              value={classData.name}
              onChange={(e) => handleChange('name', e.target.value)}
              placeholder="请输入班级名称"
            />
            {errors.name && <span style={{ color: 'red', fontSize: '12px' }}>{errors.name}</span>}
          </div>

          <div className="form-group">
            <label htmlFor="stage">阶段 *</label>
            <select
              id="stage"
              value={classData.stage}
              onChange={(e) => handleChange('stage', e.target.value)}
            >
              <option value="">请选择阶段</option>
              {stageOptions.map(option => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
            {errors.stage && <span style={{ color: 'red', fontSize: '12px' }}>{errors.stage}</span>}
          </div>
          
          <div className="form-group">
            <label htmlFor="academy">学院 *</label>
            <select
              id="academy"
              value={classData.academy}
              onChange={(e) => handleChange('academy', e.target.value)}
            >
              <option value="">请选择学院</option>
              {academyOptions.map(option => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
            {errors.academy && <span style={{ color: 'red', fontSize: '12px' }}>{errors.academy}</span>}
          </div>

          <div className="form-group">
            <label htmlFor="headTeacherId">班主任ID</label>
            <input
              type="text"
              id="headTeacherId"
              value={classData.headTeacherId}
              onChange={(e) => handleChange('headTeacherId', e.target.value)}
              placeholder="请输入班主任ID"
            />
          </div>

          <div className="form-group">
            <label htmlFor="headTeacherName">班主任姓名 *</label>
            <input
              type="text"
              id="headTeacherName"
              value={classData.headTeacherName}
              onChange={(e) => handleChange('headTeacherName', e.target.value)}
              placeholder="请输入班主任姓名"
            />
            {errors.headTeacherName && <span style={{ color: 'red', fontSize: '12px' }}>{errors.headTeacherName}</span>}
          </div>

          <div className="form-group">
            <label htmlFor="subjects">开设科目 *</label>
            <select
              id="subjects"
              multiple
              value={classData.subjects}
              onChange={handleSubjectChange}
              style={{ height: '120px' }}
            >
              {subjectOptions.map(option => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
            <div className="subjects-select">
              {(classData.subjects || []).map(subject => {
                const subjectObj = subjectOptions.find(opt => opt.value === subject);
                return (
                  <span key={subject} className="subject-tag">
                    {subjectObj?.label || subject}
                    <button type="button" className="remove-subject" onClick={() => removeSubject(subject)}>×</button>
                  </span>
                );
              })}
            </div>
            {errors.subjects && <span style={{ color: 'red', fontSize: '12px' }}>{errors.subjects}</span>}
          </div>

          <div className="form-group">
            <label htmlFor="status">状态</label>
            <select
              id="status"
              value={classData.status}
              onChange={(e) => handleChange('status', e.target.value)}
            >
              {statusOptions.map(option => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
          </div>
        </div>
        <div className="modal-footer">
          <button className="cancel-btn" onClick={onClose}>取消</button>
          <button className="save-btn" onClick={handleSave}>
            保存
          </button>
        </div>
      </div>
    </div>
  );
};

export default AddEditClassModal;